import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_novel/config/response_model.dart';
import 'package:flutter_novel/detail/data/repository/home_repository.dart';
import 'package:flutter_novel/series_list/bloc/series_list_event.dart';
import 'package:flutter_novel/series_list/bloc/series_list_state.dart';
import 'package:flutter_novel/series_list/data/model/cartoon_model_entity.dart';
import 'package:flutter_novel/widget/loading_util.dart';

class SeriesListBloc extends Bloc<SeriesListEvent, SeriesListState> {
  SeriesListBloc() : super(SeriesListState()) {
    on<GetSeriesListDataEvent>(_onGetSeriesListData);
  }

  void _onGetSeriesListData(GetSeriesListDataEvent event, Emitter<SeriesListState> emit) async {
    int page = state.page;
    int pageSize = 20;
    if (event.isRefresh) {
      page = 1;
    } else {
      page++;
    }
    LoadingUtil.show();
    ResponseModel model = await HomeRepository.getListData<CartoonModelData>(page);
    CartoonModelData? carDataModel = model.data;
    LoadingUtil.dismiss();
    if ((carDataModel?.feeds ?? []).isNotEmpty) {
      if (event.isRefresh) {
        state.list.clear();
      }
      state.list.addAll(carDataModel?.feeds ?? []);
      var nState = state.clone()
        ..page = page
        ..hasNext = page < 4
        ..loadFinish = true;
      emit(nState);
    } else {
      emit(state.clone()..loadFinish = true);
    }
  }
}
